package com.wiz.weixin.controllor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wiz.weixin.manager.MaterialManager;

/**
 * 素材
 * @author xxy
 *
 */
@Controller
@RequestMapping("/material")
public class MaterialControllor {
	private transient final Logger log=LoggerFactory.getLogger(getClass());
	@Resource
	private MaterialManager materialManager;
	/**
	 * 得到永久素材列表
	 * http://localhost:8080/material/listPermanent?type=image&offset=0&count=10
	 * @param type
	 * @param offset
	 * @param count
	 * @return
	 * @throws JSONException
	 */
	@RequestMapping(value="/listPermanent", method=RequestMethod.GET)
	public String listPermanent(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "type") String type,
			@RequestParam(value = "offset") String offset,
			@RequestParam(value = "count") String count,
			HttpSession session, Model model) throws JSONException {
		
		try {
			JSONObject jsonObject = materialManager.listPermanent(type, Integer.valueOf(offset),Integer.valueOf(count) );
			String item = jsonObject.optString("item");
			JSONArray array = new JSONArray(item);
			jsonObject = (JSONObject) array.get(0);
			return "redirect:"+jsonObject.getString("url");
		} catch (NumberFormatException e) {
			e.printStackTrace();
			log.error(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		
		return null;
		
	}
}
